<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/24
 * Time: 14:33
 */

namespace App\OpenApi\AdminApi\Admin;

use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\Core\Admin\User\AdminUserListService;
use App\Service\Core\Admin\User\AdminUserService;
use App\Service\Core\Admin\User\AdminUserStoreService;
use App\Service\OpenApi\AdminApi\OpenBaseApi;

class AdminUserApi extends OpenBaseApi
{
    public function index(): array
    {
        $list_res = (new AdminUserListService())
            ->setFields(['*', 'role_name', 'allow_edit'])
            ->setRoleId($this->input('role_id'))
            ->setUsername($this->input('username'))
            ->setUserIds($this->input('user_ids'))
            ->setPage($this->input('page', 1), $this->input('pageSize', $this->page_size))
            ->getList();
        return alert_info(0, 'ok', $list_res);
    }

    /**
     * @return array
     * @throws \Throwable
     */
    public function store(): array
    {
        return (new AdminUserStoreService())
            ->setOperate($this->operate_id, $this->operate_by)
            ->setUsername($this->input('username'))
            ->setMobile($this->input('mobile'))
            ->setPassword($this->input('password'))
            ->setRole($this->input('role'))
            ->setStatus($this->input('status'))
            ->setRemark($this->input('remark'))
            ->store($this->input('user_id'));
    }

    public function info(): array
    {
        $info = AdminUserService::getInstance()->getOne($this->input('user_id', $this->operate_id));
        if ($info) {
            unset($info['password']);
            $role_ids = $info['role_id'] ? explode(',', $info['role_id']) : [];
            $role_names = [];
            foreach ($role_ids as $role_id) {
                $role = AdminUserRoleModel::getInstance()->getOne($role_id);
                $role_names[] = $role['name'];
            }
            $info['role_name'] = implode(',', $role_names);
        }
        return alert_info(0, 'ok', $info);
    }

    public function changeStatus(): array
    {
        return AdminUserService::getInstance()->changeStatus($this->input('user_id'), $this->input('status'), $this->operate_id, $this->operate_by);
    }

    public function rePassword(): array
    {
        $password = $this->input('oldPassword');
        $new_password = $this->input('password');
        return AdminUserService::getInstance()->updatePassword($this->operate_id, $password, $new_password, $this->operate_by);
    }

    public function resetPassword(): array
    {
        $user_id = $this->input('user_id');
        return AdminUserService::getInstance()->resetPassword($user_id, $this->operate_id, $this->operate_by);
    }

    public function deleteAdminUser()
    {
        $user_id = $this->input('user_id');
        return AdminUserService::getInstance()->deleteAdminUser($user_id, $this->operate_id, $this->operate_by, $this->app_key);
    }
}
